package com.smartcommunity.controller.excel;

import com.alibaba.fastjson.JSONObject;
import com.smartcommunity.base.common.CacheMap;
import com.smartcommunity.bean.constant.ExcelContents;
import com.smartcommunity.bean.entity.User;
import com.smartcommunity.controller.BaseController;
import com.smartcommunity.controller.excel.model.*;
import com.smartcommunity.controller.excel.tool.FileUtil;
import com.smartcommunity.entity.facelib.FaceLibPerson;
import com.smartcommunity.exception.BaseException;
import com.smartcommunity.lis.BimgClientPool;
import com.smartcommunity.log.interceptor.Log;
import com.smartcommunity.log.model.SearchLogModel;
import com.smartcommunity.log.service.LogSDK;
import com.smartcommunity.service.excel.impl.ExportExcelServiceImpl;
import com.smartcommunity.service.facelib.FaceLibService;
import com.smartcommunity.utils.ExcelUtils;
import com.smartcommunity.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * @version V1.0
 * @ClassName: ExcelExportController
 * @Description: 数据导出服务
 * @author: chenpeng
 * @Date: 2020/07/24
 * @Company:
 */
@RestController
@RequestMapping(value = "/excelExport")
@Api(value = "数据导出excelApi", tags = "数据导出excel")
@Slf4j
public class ExcelExportController extends BaseController {

    @Autowired
    private FaceLibService faceLibService;

    @Autowired
    private ExportExcelServiceImpl exportExcelService;

    @Autowired
    private BimgClientPool lis;

    @PostMapping(value = "/exportLibPerson")
    @Log(info = "excel导出人脸库")
    @ApiOperation(value = "excel导出人脸库", notes = "excel导出人脸库")
    public void exportLibPerson(@RequestBody FaceLibPerson facelibPerson, HttpServletResponse response) throws Exception {
        try {
            ApplicationHome applicationHome = new ApplicationHome(getClass());
            String path = applicationHome.getSource().getParentFile().toString() + "/tmp/comanyPeople/"+System.currentTimeMillis();
            File file = new File(path);
            FileUtil.delAllFile(path);
            file.mkdirs();
            ExcelUtils excelUtil = new ExcelUtils();
            List<FaceLibPerson> list = faceLibService.listLibPerson(facelibPerson);
            if(!CollectionUtils.isEmpty(list)){
                String picPath = path + "/照片/";
                list.forEach(p->{
                    p.setCredentialTypeCN(CacheMap.CREDENTIAL_TYPE_MAP.get(p.getCredentialType()));
                    p.setGenderCN(CacheMap.GENDER_MAP.get(p.getGender())==null?"":CacheMap.GENDER_MAP.get(p.getGender()));
                    p.setNationCN(CacheMap.NATION_MAP.get(p.getNation()));
                    if(!StringUtils.isEmpty(p.getFaceImageUrl())){
                        try {
                            byte[] bytes= lis.downLoad(p.getFaceImageUrl());
                            FileUtil.writeFile(picPath,p.getIdCardNo()+".jpg",bytes);
                        } catch (Exception e) {
                            log.error("下载图片失败！",e);
                        }
                    }
                });
            }
            excelUtil.exportExcelDownload(ExcelContents.filename_lib, ExcelContents.sheetName_lib, ExcelContents.header_lib,ExcelContents.clos_lib,  list, path+"/", ExcelContents.version_lib);
            FileUtil.downloadZipFiles(response,path);
            FileUtil.delAllFile(path);
        } catch (Exception e) {
            log.error("excel导出人脸库错误", e);
            throw new BaseException("excel导出人脸库错误", e);
        }
    }

    @PostMapping(value = "/exportVehicle")
    @Log(info = "车辆信息excel")
    @ApiOperation(value = "车辆信息excel", notes = "车辆信息excel")
    public void exportVehicle(@RequestBody VehicleModel model, HttpServletResponse response)throws Exception {
        try {
            ApplicationHome applicationHome = new ApplicationHome(getClass());
            String path = applicationHome.getSource().getParentFile().toString() + "/tmp/vehicle/"+System.currentTimeMillis();
            File file = new File(path);
            FileUtil.delAllFile(path);
            file.mkdirs();
            ExcelUtils excelUtil = new ExcelUtils();
            List list = exportExcelService.listVehicle(model,path);
            excelUtil.exportExcelDownload(ExcelContents.filename_vehicle, ExcelContents.sheetName_vehicle, ExcelContents.header_vehicle, ExcelContents.clos_vehicle, list,  path+"/", ExcelContents.version_vehicle);
            FileUtil.downloadZipFiles(response,path);
            FileUtil.delAllFile(path);
        } catch (Exception e) {
            log.error("车辆信息excel错误", e);
            throw new BaseException("车辆信息excel错误", e);
        }
    }

    @PostMapping(value = "/exportCompany")
    @Log(info = "小区单位excel")
    @ApiOperation(value = "小区单位excel", notes = "小区单位excel")
    public void exportCompany(@RequestBody BaseModel model, HttpServletResponse response)throws Exception {
        try {
            ApplicationHome applicationHome = new ApplicationHome(getClass());
            ExcelUtils excelUtil = new ExcelUtils();
            String path = applicationHome.getSource().getParentFile().toString() + "/tmp/comanyPeople/"+System.currentTimeMillis();
            File file = new File(path);
            FileUtil.delAllFile(path);
            file.mkdirs();

            List list = exportExcelService.exportCompany(model, path);
            excelUtil.exportExcelDownload(ExcelContents.filename_company, ExcelContents.sheetName_company, ExcelContents.header_company,ExcelContents.clos_company, list, path+"/", ExcelContents.version_company);
            FileUtil.downloadZipFiles(response,path);
            FileUtil.delAllFile(path);
        } catch (Exception e) {
            throw new BaseException("车辆信息excel错误", e);
        }
    }

    @PostMapping(value = "/exportCPerson")
    @Log(info = "小区单位人员excel")
    @ApiOperation(value = "小区单位人员excel", notes = "小区单位人员excel")
    public void exportCPerson(@RequestBody CompanyPersonModel model, HttpServletResponse response)throws Exception {
        try {
            ApplicationHome applicationHome = new ApplicationHome(getClass());
            String path = applicationHome.getSource().getParentFile().toString() + "/tmp/comanyPeople/"+System.currentTimeMillis();
            File file = new File(path);
            FileUtil.delAllFile(path);
            file.mkdirs();
            ExcelUtils excelUtil = new ExcelUtils();
            List list = exportExcelService.exportVillagePerson(model,path);
            excelUtil.exportExcelDownload(ExcelContents.filename_c_person, ExcelContents.sheetName_c_person, ExcelContents.header_c_person,ExcelContents.clos_c_person, list, path+"/", ExcelContents.version_c_person);
            FileUtil.downloadZipFiles(response,path);
            FileUtil.delAllFile(path);
        } catch (Exception e) {
            log.error("小区单位人员excel错误", e);
            throw new BaseException("小区单位人员excel错误", e);
        }
    }

    @PostMapping(value = "/exportDevice")
    @Log(info = "小区监控设备excel")
    @ApiOperation(value = "小区监控设备excel", notes = "小区监控设备excel")
    public void exportDevice(@RequestBody DeviceSearchModel model, HttpServletResponse response)throws Exception {
        try {
            ExcelUtils excelUtil = new ExcelUtils();
            List list = exportExcelService.exportCamera(model);
            if(model.getCameraType().equals("12")){
                excelUtil.exportExcelDownload(ExcelContents.filename_ac_device, ExcelContents.sheetName_ac_device, ExcelContents.header_ac_device, ExcelContents.clos_ac_device, list, response, ExcelContents.version_ac_device);
            }else{
                excelUtil.exportExcelDownload(ExcelContents.filename_device, ExcelContents.sheetName_device, ExcelContents.header_device,ExcelContents.clos_device, list, response, ExcelContents.version_device);
            }
        } catch (Exception e) {
            log.error("小区监控设备excel错误", e);
            throw new BaseException("小区监控设备excel错误", e);
        }
    }

    @PostMapping(value = "/exportBuilding")
    @Log(info = "小区楼栋excel")
    @ApiOperation(value = "小区楼栋excel", notes = "小区楼栋excel")
    public void exportBuilding(@RequestBody VillageModel model, HttpServletResponse response)throws Exception {
        try {
            ExcelUtils excelUtil = new ExcelUtils();
            List list = exportExcelService.exportBuilding(model);
            excelUtil.exportExcelDownload(ExcelContents.filename_building, ExcelContents.sheetName_building, ExcelContents.header_building, ExcelContents.clos_building, list, response, ExcelContents.version_building);
        } catch (Exception e) {
            log.error("小区楼栋excel错误", e);
            throw new BaseException("小区楼栋excel错误", e);
        }
    }

    @PostMapping(value = "/exportAcDevice")
    @Log(info = "小区门禁excel常量")
    @ApiOperation(value = "小区门禁excel常量", notes = "小区门禁excel常量")
    public void exportAcDevice(@RequestBody BaseModel model, HttpServletResponse response)throws Exception {
        try {
            ExcelUtils excelUtil = new ExcelUtils();
            List list = exportExcelService.exportAcDevice(model);
            excelUtil.exportExcelDownload(ExcelContents.filename_ac_device, ExcelContents.sheetName_ac_device, ExcelContents.header_ac_device, ExcelContents.clos_ac_device, list, response, ExcelContents.version_ac_device);
        } catch (Exception e) {
            log.error("小区门禁excel常量错误", e);
            throw new BaseException("小区门禁excel常量错误", e);
        }
    }

    @PostMapping(value = "/exportHouse")
    @Log(info = "小区实有房屋excel")
    @ApiOperation(value = "小区实有房屋excel", notes = "小区实有房屋excel")
    public void exportHouse(@RequestBody VillageModel model, HttpServletResponse response)throws Exception {
        try {
            ExcelUtils excelUtil = new ExcelUtils();
            List list =exportExcelService.exportHouse(model);
            excelUtil.exportExcelDownload(ExcelContents.filename_house, ExcelContents.sheetName_house, ExcelContents.header_house, ExcelContents.clos_house, list, response, ExcelContents.version_house);
        } catch (Exception e) {
            log.error("小区实有房屋excel错误", e);
            throw new BaseException("小区实有房屋excel错误", e);
        }
    }

    @PostMapping(value = "/exportPeople")
    @Log(info = "小区实有人口excel")
    @ApiOperation(value = "小区实有人口excel", notes = "小区实有人口excel")
    public void exportPeople(@RequestBody PeopleModel model, HttpServletResponse response) throws Exception{
        try {
            // 获取jar所在目录
            ApplicationHome applicationHome = new ApplicationHome(getClass());
            String path = applicationHome.getSource().getParentFile().toString() + "/tmp/people/"+System.currentTimeMillis();
            File file = new File(path);
            FileUtil.delAllFile(path);
            file.mkdirs();
            ExcelUtils excelUtil = new ExcelUtils();
            List list = exportExcelService.exportPeople(model,path);
            excelUtil.exportExcelDownload(ExcelContents.filename_people, ExcelContents.sheetName_people, ExcelContents.header_people, ExcelContents.clos_people, list, path+"/"+"", ExcelContents.version_people);
            FileUtil.downloadZipFiles(response,path);
            FileUtil.delAllFile(path);
        } catch (Exception e) {
            log.error("小区实有人口excel错误", e);
            throw new BaseException("小区实有人口excel错误", e);
        }
    }

    @PostMapping(value = "/exportPower")
    @Log(info = "小区治安力量excel")
    @ApiOperation(value = "小区治安力量excel", notes = "小区治安力量excel")
    public void exportPower(@RequestBody PowerModel model, HttpServletResponse response)throws Exception {
        try {
            // 获取jar所在目录
            ApplicationHome applicationHome = new ApplicationHome(getClass());
            String path = applicationHome.getSource().getParentFile().toString() + "/tmp/people/"+System.currentTimeMillis();
            File file = new File(path);
            FileUtil.delAllFile(path);
            file.mkdirs();
            ExcelUtils excelUtil = new ExcelUtils();
            List list = exportExcelService.exportPower(model,path);
            excelUtil.exportExcelDownload(ExcelContents.filename_power, ExcelContents.sheetName_power, ExcelContents.header_power,ExcelContents.clos_power, list, path+"/"+"", ExcelContents.version_power);
            FileUtil.downloadZipFiles(response,path);
            FileUtil.delAllFile(path);
        } catch (Exception e) {
            log.error("小区治安力量excel错误", e);
            throw new BaseException("小区治安力量excel错误", e);
        }
    }

    @PostMapping(value = "/exportVillageOrg")
    @Log(info = "行政区划excel")
    @ApiOperation(value = "行政区划excel", notes = "行政区划excel")
    public void exportVillageOrg(HttpServletResponse response,@RequestBody BaseModel model)throws Exception {
        try {
            ExcelUtils excelUtil = new ExcelUtils();
            List list = exportExcelService.exportVillageOrg(model);
            excelUtil.exportExcelDownload(ExcelContents.filename_village_org, ExcelContents.sheetName_village_org, ExcelContents.header_village_org,ExcelContents.clos_village_org, list, response, ExcelContents.version_village_org);
        } catch (Exception e) {
            log.error("行政区划excel错误", e);
            throw new BaseException("行政区划excel错误", e);
        }
    }

    @PostMapping(value = "/exportOrg")
    @Log(info = "组织机构excel")
    @ApiOperation(value = "组织机构excel", notes = "组织机构excel")
    public void exportOrg(HttpServletResponse response,@RequestBody BaseModel model) throws Exception{
        try {
            ExcelUtils excelUtil = new ExcelUtils();
            List list = exportExcelService.exportOrg(model);
            excelUtil.exportExcelDownload(ExcelContents.filename_org, ExcelContents.sheetName_org, ExcelContents.header_org,ExcelContents.clos_org, list, response, ExcelContents.version_org);
        } catch (Exception e) {
            log.error("组织机构excel错误", e);
            throw new BaseException("组织机构excel错误", e);
        }
    }

    @ApiOperation("导出操作日志")
    @Log(info = "导出操作日志列表信息",module = "操作",function = "导出")
    @RequestMapping(value = "/exportExcell",method = RequestMethod.POST)
    public void exportExcell(HttpServletResponse response, @RequestBody SearchLogModel searchLogModel) throws Exception{
        //获取当前登录用户，不是admin，只能查询自己的操作日志
        User user =getCurrentUser();
        if(user !=null && !user.isAdmin()){
            searchLogModel.setUserId(String.valueOf(user.getAccount()));
        }

        JSONObject jsonObject = LogSDK.query(searchLogModel);
        if(jsonObject.containsKey("code") &&  jsonObject.getInteger("code") == 200) {
            try {
                ExcelUtils excelUtil = new ExcelUtils();
                excelUtil.exportExcelDownload(ExcelContents.filename_log, ExcelContents.sheetName_log, ExcelContents.header_log,ExcelContents.clos_log, jsonObject.getJSONObject("data").getJSONArray("list"), response, ExcelContents.version_org);
            } catch (Exception e) {
                log.error("导出excel报错", e);
                throw new BaseException("导出excel报错",e);
            }
        }
    }

}
